package cn.jnetty.ioc.definition;

import cn.jnetty.api.annotation.JValue;
import cn.jnetty.api.exception.JnettyIocException;
import cn.jnetty.ioc.configruation.JnettyConfiguration;
import cn.jnetty.ioc.configruation.PropertiesConfiguration;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @author 猪哥亮
 * @email 1030681978@qq.com
 * @date 2020/4/3 18:29
 * 描述：
 */
public class JValueBeanDefinition extends JDefaultBeanDefinition {
    private Object bean;
    private Field field;

    public JValueBeanDefinition(JValue value, Object bean, Field field) {
        super(value,field.getType());
        this.bean = bean;
        this.field = field;
        init();
    }

    @Override
    protected void init() {
        try {
            field.setAccessible(true);
            Field modifiersField  = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
            //这里的值要从ioc中去取
            String value = JnettyConfiguration.getValue(((JValue)annotation).value());
            Class<?> aClass = field.getType();
            Object o = stringToObject(aClass, value);
            if(o != null){
                field.set(bean, o);
            }
        } catch (Exception e) {
            throw new JnettyIocException("@Value注入的异常{0}===={1}",e,bean.getClass().getName(),field.getType().getName());
        }
    }
    private Object stringToObject( Class<?> clazz,String params) {
        if(params == null){
            return null;
        }
        if (clazz.equals(int.class) || clazz.equals(Integer.class)) {
            return Integer.parseInt(params);
        } else if (clazz.equals(short.class) || clazz.equals(Short.class)) {
            return Short.parseShort(params);
        } else if (clazz.equals(byte.class) || clazz.equals(Byte.class)) {
            return Byte.parseByte(params);
        } else if (clazz.equals(boolean.class) || clazz.equals(Boolean.class)) {
            return Boolean.parseBoolean(params);
        } else if (clazz.equals(long.class) || clazz.equals(Long.class)) {
            return Long.parseLong(params);
        } else if (clazz.equals(float.class) || clazz.equals(Float.class)) {
            return Float.parseFloat(params);
        } else if (clazz.equals(double.class) || clazz.equals(Double.class)) {
            return Double.parseDouble(params);
        } else if (clazz.equals(String.class)) {
            return params;
        } else {
            return params;
        }
    }
}
